package com.itsu.application.controller;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.itsu.application.entity.User;
import com.itsu.application.framework.session.SessionContext;
import com.itsu.application.framework.websocket.WebSocketComponent;
import com.itsu.application.service.LoginService;
import com.itsu.application.util.AlertUtil;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

import java.util.List;

public class LoginController {

	private static final Log log = LogFactory.get();

	@FXML
	private TextField uid;
	@FXML
	private PasswordField pwd;
	@FXML
	private Button submit;

	private Stage stage;

	public Stage getStage() {
		return stage;
	}

	public void setStage(Stage stage) {
		this.stage = stage;
	}

	private LoginService loginService = new LoginService();

	// Event Listener on Button[#submit].onAction
	@FXML
	public void eventSubmit(ActionEvent event) {
		String userId = uid.getText();
		String password = pwd.getText();
		if (StrUtil.isBlank(userId) || StrUtil.isBlank(password)) {
			AlertUtil.alert("登录参数异常", "UserId和Password是必输的! ", AlertType.ERROR);
		} else {
			try {
				User user = loginService.login(new User(userId, password, null, null));
				if (user == null) {
					AlertUtil.alert("登录失败", "用户名或密码错误", AlertType.ERROR);
				} else {
					SessionContext.getSession().setAttribute("loginUser", user);
					handleLogin();
				}

			} catch (Exception e) {
				log.error(e);
				AlertUtil.alert("登录失败", e.getMessage(), AlertType.ERROR);
			}
		}
	}

	public void handleLogin() throws Exception {
		// 切换场景图
		FXMLLoader loader = new FXMLLoader(ResourceUtil.getResource("fxml/talk.fxml"));
		Parent root = loader.load();
		TalkController talkController = loader.getController();
		ListView myFrends = talkController.getMyFrends();
		User user = (User) SessionContext.getSession().getAttribute("loginUser");
		List<String> friends = loginService.getFriendsIdName(user);
		ObservableList<String> items = FXCollections.observableArrayList(friends);
		myFrends.setItems(items);
		myFrends.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {

			@Override
			public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
				WebView showText = talkController.getShowText();
				talkController.setWebViewContent("<h3 style='text-align: center'>正在与 " + newValue + "聊天</h3>");
				talkController.setToUserNameId(newValue);
				WebEngine engine = showText.getEngine();
				engine.loadContent(talkController.getWebViewContent());
			}

		});
		this.stage.setScene(new Scene(root));
		WebSocketComponent.connect("ws://localhost:8100/socket/" + user.getUserId(),
				MapUtil.builder("token", "token").build());
	}
}
